<?php
// customer manage
namespace Admin\Controller;
use Think\Controller;
use Common\Controller\BaseController;

class ComplainController extends BaseController {
		// get condition of judging shown or hidden
		public function shownorhidden(){
			$Mcomplain  = D('Admin/User','Service','Admin');
			$Mres = $Mcomplain->authWithKey($this->m_user['user_id'],'COMPLAIN_VIEW_HIDE');
			$showorhide = $Mres['rcode'];	
			e_json($showorhide);		
		}

		// customercomplain list 
		public function index()
		{
			$wheres = array();
			$wheres['_string'] = '1=1';

			$state = I('get.state', -1,'intval');
			$psize = I('get.psize', $this->m_psize,'intval');
			// $title = I('get.title', '', 'trim');
			$customer = I('get.customer', '', 'trim');
			$content = I('get.content','','trim');
			$showhide = I('get.shownorhiddenfield','','intval');
			// $stime = 	I('get.stime', '', 'trim');
			// $etime = I('get.etime', '', 'trim');
			$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
			if( $state != -1 ){
				if($state == 0){
					$wheres['cp.status'] = 0;
				}else{
					$wheres['cp.status'] = array('eq',$state);
				}						
			}
			$Mdo = D('Admin/CustomerComplain');

			// if( $stime && $etime ){
			// 	$tm_s = strtotime( $stime );
			// 	$tm_e = strtotime( $etime );
			// 	$wheres['cp.create_time'] = array('between', array(date('Y-m-d 0:0:0', $tm_s), date('Y-m-d 23:59:59', $tm_e ) ) );
			// }
			// else if( $stime ){
			// 	$tm_s = strtotime( $stime );
			// 	$wheres['cp.create_time'] = array('gt', date('Y-m-d 0:0:0', $tm_s) );
			// }
			// else if( $etime ){
			// 	$tm_s = strtotime( $etime );
			// 	$wheres['cp.create_time'] = array('lt', date('Y-m-d 23:59:59', $tm_s) );
			// }
			if( $customer ){
				$map = array();
				if(strlen($customer) && is_numeric($customer))$map['cp.customer_phone'] = array('like', '%'.$customer.'%');
				$map['cp.customer_name'] = array('like', '%'.$customer.'%');
				$map['a.customer_code'] = array('like','%'.$customer.'%');
				$map['_logic'] = 'or';				
				$wheres['_complex'] = $map;
			}
			if($content){
				$wheres['cp.content'] = array('like','%'.$content.'%');
			}

			if( !$psize )
				$psize = $this->m_psize;
			else if( $psize > 20 )
				$psize = $this->m_psize;
			if(!$this->m_is_admin){// only can judge the right is of admin or is of cutomer 
				$MSector = D('Admin/Sector');
				$wheres['cp.sub_company'] = $MSector::parent_company( $this->m_user['sector_id'] );	
			}
 			if(!$showhide) $wheres['cp.is_hide'] = array('eq',11);
			$wheres['cp.is_delete'] = array('neq', 1);
			$cnt = $Mdo
						->alias("cp")
						// ->field('cp.create_time,cp.customer_name,cp.state,cp.content')
						->join('LEFT JOIN customer as a ON a.customer_id = cp.customer_id')
						->where( $wheres )
						->count();
			$Page = new \Common\ORG\Page( $cnt, $psize );

			/**2017-07-04 wjw 添加客户浮窗开始**/
			$dlist = $Mdo->alias("cp")
						->field('cp.create_time,cp.customer_name,cp.status,cp.content,cp.complain_id,cp.is_hide,cp.incoming_type,a.customer_id')
						->join('LEFT JOIN customer as a ON a.customer_id = cp.customer_id')
						->where( $wheres )
						->order("cp.create_time desc ")
						->limit($Page->firstRow.','.$Page->listRows )
						->select();
			foreach ($dlist as &$value) {
				if(!empty($value['customer_id'])){
					$value['isCustomer'] = 1;
				}else{
					$value['isCustomer'] = 2;
				}
			}
			/**添加客户浮窗结束**/
			if($dlist){
				$res['rcode'] = 1;
				$res['data'] = $dlist;
				$res['pall'] =  $Page->getTotalPages();
				$res['p'] = $Page->nowPage;
				$res['psize'] = $psize;
				$res['showorhidden'] = $showhide;
				$res['is_admin'] = $this->m_is_admin;
				$res['state'] = $state;
			}else{
				$res['is_admin'] = $this->m_is_admin;
				$res['state'] = $state;
				$res['showorhidden'] = $showhide;
			}
			e_json($res);
		}
		// delete complain records
		// public function del(){
		// 	$r = array('r'=>0,'i'=>'server error','d'=>NULL );
		// 	$id = I('get.id',false,'intval');
		// 	if( !$id ){
		// 		$res['msg'] = L('PARAM_WRONG');
		// 	}
		// 	else{
		// 		$MCus = D('customer_complain');
		// 		$wheres = array();
		// 		$wheres['complain_id'] = array('eq', $id);
		// 		$wheres['is_delete'] = array('neq', 1);
		// 		$find = $MCus->where( $wheres )->find();
		// 		if( $find ){
		// 			$d = array();
		// 			$d['is_delete'] = 1;
		// 			if(  $MCus->where( $wheres )->save( $d ) ){
		// 				$r['r'] = 1;
		// 				$r['i'] = 'OK';
		// 			}else{
		// 				$r['i'] = L('DATA_DELETE_ERR');
		// 			}
		// 		}
		// 		else
		// 			$r['i'] = L('NO_DATA');
		// 	}
		// 	e_json( $r);
		// }
		// edit complain records
		public function edit(){
			$res = array('rcode'=>-1,'msg'=>'服务器忙，请稍候再试','data'=>null);
			$id = I('get.complain_id',false,'intval');
			$info = I('get.info','','trim');
			$state = I('get.state',false,'intval');
			$MCus = D('customer_complain');
			$Cusres = $MCus->editCustomer($id,$info,$state);
			if( $Cusres['r'] ){
				$res['rcode'] = 1;
				$res['msg'] = 'OK';
				$res['data'] = $Cusres['data'];
			}
			else{
				$res['msg'] = $Cusres['i'];
			}
			e_json($res);

		}

		// get customer message
		public function getmessage(){
			$res = array();
			$att = array();
			$id = I('get.id',false,'intval');
			$Cus = M('Customer_complain');
			$repres = M('customer_complain_reply');
			$att['complain_id'] =  $id;
			$rback = $repres -> where($att)->select();
			$res = $Cus	-> where('complain_id='.$id)->order('customer_complain.create_time desc')->find();
		    e_json($res);
		}
		public function getres(){
			$att = array();
			$id = I('get.id',false,'intval');
			//$customer = I('get.customer','','trim');
			$repres = M('customer_complain_reply');
			$att['complain_id'] =  $id;
			$rback = $repres ->field('user.nickname,customer_complain_reply.content,customer_complain_reply.create_time')->join('user ON  customer_complain_reply.user_id = user.user_id')-> where($att)->select();
			//$rback['res'] = $customer;
		    e_json($rback);
		}
		// public function getproduct(){

		// 	$Product=M("product");
		// 	$user = M('user');
		// 	$res = D('customer_complain');
		// 	// $Uid = $res->uidback();
		// 	$uninres = $user ->field('sector.parent_company')->join('sector ON user.sector_id = sector.sector_id')
		// 					 ->where(array('user_id'=>$this->m_user['user_id']))
		// 					 ->select();
		// 	$wheres = array();
		// 	$wheres['sub_company'] = intval($uninres);
		// 	$Pres = $Product->field('product_id,name')->where($wheres)->select();
		//     echo json_encode( array("product"=>array_values($Pres)));
		// 	exit();
		// }
		// add complain message
		public function add(){
			$res = array('rcode'=>0,'msg'=>'error','data'=>null);
			$login_name = I('post.Cname','','trim');
			// $title = I('post.Ctitle','','trim');
			$contact = I('post.Ccontact',false,'trim');
			$content = I('post.info','','trim');
			$calltypeextra = I('post.calltypeextra',false,'intval');
			$User = M('user');
			$customercomplain = D('customer_complain');
			// $Uid = $customercomplain->uidback();
			$Ur = $User ->where(array('user_id'=>$this->m_user['user_id']))->find();
			$arr = $cus_add = $riskarr = array();
			// $uninres = $User ->field('sector.parent_company')->join('sector ON user.sector_id = sector.sector_id')
			// 				 ->where(array('user_id'=>$this->m_user['user_id']))
			// 				 ->find();
			$uninres = $User ->join('sector ON user.sector_id = sector.sector_id')
							 ->where(array('user_id'=>$this->m_user['user_id']))
							 ->find();
			if($uninres['is_subcompany'] == 1){
				$arr['sub_company'] = intval($uninres['sector_id']);
			}else{
				$arr['sub_company'] = intval($uninres['parent_company']);
			}
			$arr['creator_sector'] = $Ur['sector_id'];
			$arr['creator_role'] = $Ur['role_id'];
			$arr['creator'] = $this->m_user['user_id'];
			$arr['customer_name'] = $login_name;
			//查询phonebook中电话号码对应客户id
			$contactRes = M('customer_phonebook')->where(array('book_phone'=>$contact))->find();
			if ($contactRes) {
				$arr['customer_id']=$contactRes['customer_id'];
				if($calltypeextra == 31){
					$customerRes = M('customer')->field('sales_person,sales_sector,sales_manager,sales_sub_company')->where(array('customer_id'=>$contactRes['customer_id']))->find();
					if($customerRes){
						$cus_add['sales_id'] = $customerRes['sales_person'];
						$cus_add['sales_sector'] = $customerRes['sales_sector'];
						$cus_add['sales_manager'] = $customerRes['sales_manager'];
						$cus_add['sales_subcompany'] = $customerRes['sales_sub_company'];
						$cus_add['customer_id'] = $contactRes['customer_id'];
						$cus_add['customer_name'] = $login_name;
						$cus_add['customer_phone'] = $contact;
						$cus_add['description'] = $content;
						$cus_add['remark'] = '来自投诉';
						$cus_add['create_time'] =  date('Y-m-d H:i:s');
					}
					$cus_res = M('risk')->add($cus_add);
					//若为投诉关联到complain表
					if($cus_res){
						$arr['risk_id'] = $cus_res;
					}
					// if($cus_res){
					// 	$riskarr['risk_id'] = $cus_res;
					// 	$riskarr['reply'] = '400电话投诉';
					// 	$riskarr['is_delete'] = 0;
					// }	
					// $riskaddres = M('risk_track')->add($riskarr);			
				}
			}else{
				if($calltypeextra == 31){
						$cus_add['customer_name'] = $login_name;
						$cus_add['customer_phone'] = $contact;
						$cus_add['description'] = $content;
						$cus_add['remark'] = '来自投诉';
						$cus_add['create_time'] =  date('Y-m-d H:i:s');		
						$cus_res = M('risk')->add($cus_add);			
				}
				
				/*	WJW 2017-07-25 
				*	风险添加成功后返回id 更新complain表中的risk_id 
				*	与数据绑定 开始
				*/


				/*
				*	修改结束
				*/


				// if($cus_res){
				// 	$riskarr['risk_id'] = $cus_res;
				// 	$riskarr['reply'] = '400电话投诉';
				// 	$riskarr['is_delete'] = 0;
				// }
				// $riskaddres = M('risk_track')->add($riskarr);				
			}
			if (preg_match('#^\d+$#is', $contact )) {
				if (strlen( $contact) == 11 ) {
					$arr['customer_phone'] = $contact;
				}
			}

			$arr['risk_id'] = isset($cus_res)?$cus_res:NULL;
			$arr['content'] =  $content;
			$arr['incoming_type'] = $calltypeextra;
			$arr['create_time'] = date('Y-m-d H:i:s');
			$arr['status'] = 0;
			$arr['is_hide'] = 11;
			$cid = $customercomplain->add($arr);
			if ($cid) {
				$res['rcode'] = 1;
				$res['msg']='ok';
				$res['data'] = $customercomplain->where('complain_id='.$cid)->find();
			}
			e_json($res);
		}

	// export conflictRecords
	public function exportRecords(){
		$wheres = $res = array();
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$GET = $_GET;
		$customer = I('get.customer','','trim');
		$content = I('get.content','','trim');
        // if($GET['customer'])                                     	   $wheres['a.customer_name'] = array('like',"%".$GET['customer']."%");
		if( $customer ){
			$map = array();
			if(strlen($customer) && is_numeric($customer))$map['a.customer_phone'] = array('like', '%'.$customer.'%');
			$map['a.customer_name'] = array('like', '%'.$customer.'%');
			$map['b.customer_code'] = array('like','%'.$customer.'%');
			$map['_logic'] = 'or';				
			$wheres['_complex'] = $map;
		}
        if($content)                                            $wheres['a.content'] =array('like',"%".$content."%");
		if($GET['state'] == 0)                  					   $wheres['a.status'] = 0;  
		if($GET['state'] && $GET['state'] != -1 )                  	   $wheres['a.status'] = array('eq',$GET['state']);
 																	   $wheres['_string'] = '1=1';
																	   $wheres['a.is_delete'] = array('neq',1);
			if(!$this->m_is_admin){
				$MSector = D('Admin/Sector');
				$wheres['a.sub_company'] = $MSector::parent_company( $this->m_user['sector_id'] );	
			}
			// if(!$showorhide) $wheres['a.is_hide'] = array('eq',11);
		// reference
		import("Common.ORG.Excel");
		$SExcel = new \Common\ORG\Excel();
		$SSheet = new \Common\ORG\Sheet("投诉记录数据");

		$rescomplain = D('Admin/CustomerComplain') 
														->field('a.complain_id,a.create_time,a.customer_name,a.customer_phone,a.incoming_type,a.content,a.status')
														->alias("a")
														->join('LEFT JOIN customer as b ON b.customer_id = a.customer_id')
														->where($wheres)
														->order('a.create_time desc')
														->select();
		foreach($rescomplain as $key =>$value){
			$rescomplainreply = M('CustomerComplainReply')
														->field('content')
														->where(array('is_delete'=>array('neq',1),'complain_id'=>$value['complain_id']))
														->order('create_time desc')
														->limit(1)
														->select();
			$rescomplain[$key]['rescustomercomplainreply'] = $rescomplainreply[0]['content'];
		}	
		// e_json($rescomplain);						
		// set table header content 
		$column = array('投诉时间','客户姓名','电话','投诉类型','投诉内容','是否完结','最终处理结果');
		$SSheet->setColumn( $column );		

		if( $rescomplain ){
			foreach($rescomplain as $vd ){
				$row = array();
				$row[] = $vd['create_time'];
				$row[] = $vd['customer_name'];
				$row[] = $vd['customer_phone'];
				$incoming_type = intval( $vd['incoming_type'] );
				$row[] = $incoming_type == 11 ? '日常事务':( $incoming_type==21 ? '广告':( $incoming_type == 31 ? '投诉' : '其他') );
				$row[] = $vd['content'];
				$state = intval($vd['status']);
				$row[] = $state == 0 ?'未处理':($state == 1?'处理中':($state == 2 ?'已解决':'已挂起'));
				$row[] = $vd['rescustomercomplainreply'];
 				$SSheet->addRow( $row );
			}
		}
		$exportData = $SExcel->add_sheet( $SSheet)->export_sheet("客户投诉记录导出");
		if( $exportData['rcode'] ){
			$exportData['name'] = basename( $exportData['data']['view_path'] );
			$exportData['excel'] = file_get_contents( $exportData['data']['real_path'] );
			echo $exportData['excel'];
			exit();
		}
	}

	// hide complain records
	public function hideComplainRecord(){
		$res = array('rcode'=>0,'msg'=>'error','data'=>null);
		$hiddeId = I('post.hiddeID','','intval');
		$hiddeRes = M('customer_complain')->where(array('complain_id'=>$hiddeId))->save(array('is_hide'=>11));
		if($hiddeRes){
			$res['rcode'] = array('eq',1);
			$res['msg'] = 'ok';
			$res['data'] = M('customer_complain')->where(array('complain_id'=>$hiddeId))->find();
		}
		e_json($res);
	}

	// show complain records
	public function showComplainRecord(){
		$res = array('rcode'=>0,'msg'=>'error','data'=>null);
		$showId = I('post.showId','','intval');
		$hiddeRes = M('customer_complain')->where(array('complain_id'=>$showId))->save(array('is_hide'=>1));
		if($hiddeRes){
			$res['rcode'] = array('eq',1);
			$res['msg'] = 'ok';
			$res['data'] = M('customer_complain')->where(array('complain_id'=>$showId))->find();
		}
		e_json($res);		
	}

}
